import React, { Component } from 'react'
import Counter from './Counter'
import store from './stateFactory/Store'
class Controlpannel extends Component {
  constructor (props) {
    super(props)
    this.onChange = this.onChange.bind(this)
    this.state = this.getOwnState()
  }
  getOwnState () {
    const state = store.getState()
    let sum = 0
    for (let x in state) {
      if (state.hasOwnProperty(x)) {
        sum = sum + state[x]
      }
    }
    return {sum, ...state}
  }
  onChange () {
    this.setState(this.getOwnState())
  }
  // 保持组件内state与store中的一致
  componentDidMount () {
    store.subscribe(this.onChange)
  }
  componentWillUnmount () {
    store.unsubscribe(this.onChange)
  }
  render () {
    return (
      <div>
        <Counter caption="First" initValue={ this.state['First'] } />
        <Counter caption="Second" initValue={ this.state['Second'] } />
        <Counter caption="Third" initValue={ this.state['Third']} />
        <button onClick={() => this.forceUpdate()}>
          Click me to repaint
        </button>
        <p>total: {this.state.sum}</p>
      </div>
    )
  }
}
export default Controlpannel